Skip to content

add all classes#5

Open
VS-Ivanov wants to merge 1 commit into
masterfrom
hw11
Open

add all classes#5
VS-Ivanov wants to merge 1 commit into
masterfrom
hw11

Conversation

@VS-Ivanov

Copy link
Copy Markdown
Owner

No description provided.

return time;
}

abstract int initSwimCost();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Этот метод лишний

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Этот метод нужен для инициализации значения SwimCost у всех водоплавающих. Так как он абстрактный, то любое водоплавающее животное его реализует и это гарантирует, что всегда будет поле с названием SwimCost и оно всегда будет проинициализировано своим значением для конкретного животного.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опять же, идея не моя https://stackoverflow.com/questions/2613596/how-to-create-an-abstract-field
Использовал рекомендацию, которая показалась наиболее простой "using the Template pattern. In this way, you force all subclasses to implement the init() method, which, since it being called by the constructor, will assign the field for you."

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Там у человека хитрый случай, в данном решении такой подход не требуется

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Спорить не буду, вы профи, вам виднее

package ru.otus.vadim.ivanov.java.basic.lesson11.oop2;

//обычные животные
public abstract class Animal {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По заданию требовался еще флаг усталости, чтобы в методе инфо потом сказать что животное устало по результату гонки

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В задаче нет ничего про флаг усталости, цитирую "Если выносливости не хватает, то возвращаем время -1 и указываем что у животного появилось состояние усталости. "

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавляем метод info(), который выводит в консоль состояние животного.

Как Вы отпечатаете состояние усталости если не отслеживаете его?)

Но согласен, можно сослаться на нечуткую формулировку дз и не делать это)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Состояние это текущее значение выносливости, просто вывожу его в консоль.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ок, согласен, вопрос снят)

String name;

//скорость бега м/с
private int runSpeed;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему это поле закрыто от наследников?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Принцип инкапсуляции говорит о том, что все что не используется явно, должно быть закрыто. Да и вы сами об этом говорили, открыть то, что необходимо. В предлагаемой мной реализации необходимости его открывать нет.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не совсем так, давайте в общем чате обсудим

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ок

package ru.otus.vadim.ivanov.java.basic.lesson11.oop2;

//обычные животные
public abstract class Animal {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Всех животных стоило бы вынести в отдельный пакет

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В задании это явно нигде не прописано. Ошибку понял, учту на будущее.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну задание не должно описывать те вещи, о которых должен заботиться сам программист

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для человека который ничего не разрабатывал на яве, это не совсем очевидно. К тому же, вы при демонстрации примеров часто делаете каждый класс в отдельном файле в том же пакете

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Согласен, на занятии могу это не часто показывать, и поэтому проговариваю это на ревью кода. Ревью домашек это дополнительный материал для изучения в том числе

int endurance;

//Все животные на 1 метр бега тратят 1 ед выносливости
private final int runCost = 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

private final int DEFAULT_RUN_COST = 1;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ошибка, согласен.

}

endurance -= actionCost;
int time = distance/runSpeed;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Время лучше бы флоатом считать

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В задании опять же не сказано, что нужна точность до мс. Почему нельзя использовать точность до секунды? Int для этого вполне достаточно.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Эх.. и правда про флоат не написал, ответ принимается)

super(name,runSpeed,endurance);
this.swimSpeed = swimSpeed;

this.swimCost = initSwimCost();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это поле можно спокойно заполнять в конструкторе конкретного животного

@VS-Ivanov VS-Ivanov Aug 11, 2023

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Правильную инициализацию этого поля мы оставляем на совесть разработчика, который будет писать конструктор конкретного животного, что опять же по моему мнению (не факт что истинному) не правильная стратегия. Необходимость реализовать initSwimCost - гарантирует наличие этого поля и его правильную инициализацию.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А что мешает совести разработчика криво заполнить поле в initSwimCost? Если оно прошито в родительском конструкторе, то сам родительский конструктор не даст его пропустить

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну как бы они его не заполняли, метод должен вернуть int и наше поле тоже типа int, а значит работа алгоритма не нарушится, мы всегда получим int. Ошибка может быть только в самом значении, но от этого уже застраховать не возможно, ну или накручивать логику валидации

package ru.otus.vadim.ivanov.java.basic.lesson11.oop2;

//водоплавающие
public abstract class WaterfowlAnimal extends Animal {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

При такой структуре классов будет крайне сложно "смешивать" способности животных. Например, если добавилась бы логика травоядные(т)/хищные(х), то строилось бы большое дерево, плав/т, п/х, неплав/т, нп/х. А если добавим сюда третье свойство, то при добавлении придется переписывать все классы, чтобы переразнести их в разные группы

Всю реализацию можно было оставить в Животном, только при попытке попросить поплавать кота, он бы просто отказывался от этого.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Согласен, сложно. Возможно я не правильно понял задание "Кот плавать не умеет." - я понимаю как, у кота в принципе не должно быть метода swim, а как это реализовать без разделения на группы? Идея, про то, что у кота есть метод swim, но он при этом ничего не делает не совсем очевидна. А что метод swim будет возвращать? По условию он должен возвращать время или -1 в случае усталости.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-1 скорее по логике означает невозможность выполнить действие, поэтому у кота свим может быть (типа попросим его поплавать), но он скажет нет и просто вернет -1

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это ни разу не очевидно "Если выносливости не хватает, то возвращаем время -1"

//водоплавающие
public abstract class WaterfowlAnimal extends Animal {

private int swimCost;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему эти поля приватные?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Они не используются нигде кроме текущего класса, зачем их делать открытыми ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants